CC = $(CROSS)g++
AR = $(CROSS)ar -r
SR = $(CROSS)g++ -shared
LD = $(CROSS)ld 

TARGET   := runtest
BUILDIN  := build-in.o

SUBDIRS = source

SRC_FILES := $(wildcard *.cpp)
OBJ_FILES := $(SRC_FILES:.cpp=.o)

SUB_FILES := $(addsuffix /$(BUILDIN),$(SUBDIRS))
EXT_FILES := $(OUTDIR)/libtestbench.a
#EXT_FILES += $(PWD)/TestBench/library/libpcap/lib/$(CROSS)libpcap.a
#EXT_FILES += $(PWD)/out/third/lib/libtermcap.a
#EXT_FILES += $(PWD)/out/third/lib/libreadline.a
#EXT_FILES += $(PWD)/out/third/lib/libhistory.a

subdir     := $(addprefix build_,$(SUBDIRS) )
clean_dirs := $(addprefix clean_,$(SUBDIRS) )

#WARNINGS = -Wall -Wextra -Werror -Wfatal-errors
#WARNINGS = -Wall
INCLUDE_DIRS = -I$(PWD)/TestMain \
               -I$(PWD)/TestMain/source \
               -I$(PWD)/TestBench/include \
               -I$(OUTDIR)/third/include

CFLAGS  += -O2 -Os -fPIC
CFLAGS  += $(WARNINGS) $(INCLUDE_DIRS)
CFLAGS  += -L$(PWD)/out/third/lib

LD_FLAGS += -L$(OUTDIR)/third/lib -lpthread 
LD_FLAGS += -ldl

export CROSS
export BUILDIN
export CFLAGS
export PWD

# default rule
default: all

# non-phony targets
$(TARGET):
	@echo "LD vvv $(TARGET)"
	$(CC) -o $(TARGET) $(LD_FLAGS) $(OBJ_FILES) $(SUB_FILES) $(EXT_FILES)
	@cp $(TARGET) $(OUTDIR)/

$(OBJ_FILES): %.o:%.cpp
	$(CC) $(CFLAGS) -o $@ $<

$(SUBDIRS):
	make -C $@

$(subdir):
	@echo "CC  $@"
	$(MAKE) -C $(patsubst build_%,%,$@)

$(clean_dirs):
	rm -rf $(TARGET)
	$(MAKE) -C $(patsubst clean_%,%,$@) clean

# phony rules
.PHONY: all 
all: $(clean_dirs) $(subdir) $(TARGET)

.PHONY: clean
clean: $(clean_dirs)
	rm -rf $(TARGET)
	rm -rf *.o

